package com.autotest.nore.common.request;

import com.autotest.nore.common.constants.RequestPath;
import com.autotest.nore.common.exception.TokenEmptyException;
import org.springframework.web.servlet.HandlerInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     * 基于URL实现的拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getServletPath();
        if (path.matches(RequestPath.LOGIN_PATH.path) || path.matches(RequestPath.ENGINE_TOKEN_PATH.path)
                || path.matches(RequestPath.REGISTER_PATH.path) || path.matches(RequestPath.SCREENSHOT_PATH.path)
                || path.matches(RequestPath.DOWNLOAD_PATH.path) || path.matches(RequestPath.RUN_PATH.path)) {
            // 平台登录注册接口 引擎获取token接口 测试截图预览 不用拦截
            return true;
        } else if (path.matches(RequestPath.ENGINE_PATH.path)){
            // 引擎拦截验证
            String token = request.getHeader("token");
            if (token == null){
                throw new TokenEmptyException("token不能为空");
            }
            return true;
        } else {
            // 平台拦截验证
            String token = request.getHeader("token");
            if (token == null){
                throw new TokenEmptyException("token不能为空");
            }

            return true;
        }
    }
}
